import { Injectable } from '@nestjs/common';
import UploadQiniu from '@/utils/qiniu';
import * as path from 'path';
import { Readable } from 'stream';
import sharpFile from '@/utils/sharp';
@Injectable()
export class UploadService {
  constructor() {}
  async uploadAvator(file): Promise<any> {
    const extname = path.extname(file.originalname);
    if (file?.mimetype?.indexOf('webp') !== -1) {
      const filename = 'avator/bj_' + Date.now() + '.webp';
      const qiniu = new UploadQiniu();
      const stream = await (
        await sharpFile(Readable.from(file.buffer))
      ).toWebp();
      const imgSrc = await qiniu.upload({
        filename: filename,
        readableStream: stream,
      });
      return imgSrc;
    }
    const filename = 'avator/bj_' + Date.now() + extname.toLocaleLowerCase();
    const qiniu = new UploadQiniu();
    const imgSrc = await qiniu.upload({
      filename: filename,
      readableStream: Readable.from(file.buffer),
    });
    return imgSrc;
  }
  async uploadFile(file): Promise<any> {
    // const extname = path.extname(file.originalname);
    const filename = 'bj_' + Date.now() + '.webp';
    const qiniu = new UploadQiniu();
    const stream = await (await sharpFile(Readable.from(file.buffer))).toWebp();
    const imgSrc = await qiniu.upload({
      filename: filename,
      readableStream: stream,
    });
    return imgSrc;
  }
  async compress(file): Promise<any> {
    // const extname = path.extname(file.originalname);
    const qiniu = new UploadQiniu();
    const filename = 'bj_' + Date.now();
    const stream1 = await (await sharpFile(Readable.from(file.buffer))).toPng();
    await qiniu.upload({
      filename: filename + '.png',
      readableStream: stream1,
    });

    const stream = await (await sharpFile(Readable.from(file.buffer))).toWebp();
    const imgSrc = await qiniu.upload({
      filename: filename + '.webp',
      readableStream: stream,
    });
    return imgSrc;
  }
}
